package com.totem.admin.service.impl;

import com.totem.admin.service.IAdminCustomerService;
import com.totem.base.CacheHolder;
import com.totem.base.constants.CacheConstants;
import com.totem.base.constants.CommonConstants;
import com.totem.base.constants.ErrorCode;
import com.totem.base.exception.BaseException;
import com.totem.base.mybatis.UserIdContext;
import com.totem.customer.mapper.TLoginJournalMapper;
import com.totem.customer.model.TCustomers;
import com.totem.customer.model.TLoginJournal;
import com.totem.customer.serivce.ITCustomerService;
import com.totem.customer.vo.CustomerLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class AdminCustomerServiceImpl implements IAdminCustomerService {
    @Autowired
    private CacheHolder cacheHolder;
    @Autowired
    private TLoginJournalMapper tLoginJournalMapper;
    @Autowired
    private ITCustomerService itCustomerService;
    @Override
    public CustomerLoginVO login(CustomerLoginVO vo) {
        log.info("user {} login by {}", vo.getNickname(), vo.getPassword());

        Long userId = UserIdContext.getUserId();
        if(userId==null){
            throw new BaseException(ErrorCode.UNAUTHORIZED);
        }
        TCustomers tCustomers = itCustomerService.getById(userId);
        if(tCustomers==null){
            throw new BaseException(ErrorCode.NOT_EXIST_CUSTOMER);
        }
        BeanUtils.copyProperties(tCustomers, vo);
        vo.setCustomerId(userId);
        vo.setPassword(null);

        // 判断管理员角色
        String nickname = tCustomers.getNickname();
        if(StringUtils.isNotBlank(nickname)){
            if(CommonConstants.DEFAULT_ADMIN.equalsIgnoreCase(nickname)){
                vo.setRoles(CommonConstants.DEFAULT_ADMIN);
            }else if(CommonConstants.DEFAULT_FINANCIAL.equalsIgnoreCase(nickname)){
                vo.setRoles(CommonConstants.DEFAULT_FINANCIAL);
            }else if(CommonConstants.DEFAULT_OPERATION.equalsIgnoreCase(nickname)){
                vo.setRoles(CommonConstants.DEFAULT_OPERATION);
            }else{
                vo.setRoles(null);
            }
        }

        Object tokenObj = cacheHolder.get(CacheConstants.CACHE_TOKEN +userId);
        if(tokenObj==null){
            throw new BaseException(ErrorCode.UNAUTHORIZED);
        }
        String token = tokenObj.toString();
        vo.setToken(token);

        TLoginJournal loginJournal = TLoginJournal.builder()
                .customerId(userId)
                .nickname(vo.getNickname())
                .email(vo.getEmail())
                .countryCode(vo.getCountryCode())
                .mobile(vo.getMobile())
                .build();
        tLoginJournalMapper.insert(loginJournal);
        return vo;
    }
}
